import './graphDrawerContent.css'

import { Tabs, Timeline, Spin } from 'antd'
import { selectedDisputeThumbnailAtom } from '@/app/atoms'
import { useSetAtom, useAtomValue } from 'jotai'
import { CloseOutlined } from '@ant-design/icons'
import { PoliceCase, JointInvestigation } from './Case'
import BasicInfo from './BasicInfo'
import { useQuery } from '@tanstack/react-query'
import { useState, useEffect } from 'react'
import { apiClient } from '@/lib/apiClient'
import { arrayHelper } from '@/utils/common'

function Close () {
    const setSelectedDisputeThumbnailAtom = useSetAtom(selectedDisputeThumbnailAtom)

    const handleClickClose = () => {
        setSelectedDisputeThumbnailAtom(() => (undefined))
    }

    return (
        <CloseOutlined style={{ fontSize: 14 }} onClick={handleClickClose}/>
    )
}

function DisputeInfoContainer () {

    const selectedDisputeThumbnail = useAtomValue(selectedDisputeThumbnailAtom)
    const { data, status } = useQuery({
        queryKey: ['graph_dispute_info', selectedDisputeThumbnail?.id],
        queryFn: async () => {
            const data = await apiClient.post(
                `graphAnalysis/disputeInfo`,
                {
                    json: {
                        disputeId: selectedDisputeThumbnail?.id,
                    }
                },
            ).json()

            return data
        },
        enabled: !!selectedDisputeThumbnail?.id,
        select: (result) => {
            if (result.code === 200) {
                if (result.data?.disputeSource === '110警情') {
                    return {
                        type: 'police_case',
                        date: result.data?.alarmTime,
                        title: result.data?.disputeType,
                        content: result.data?.alarmContent,
                        feedback: result.data?.policeResponse,
                        policeCaseNumber: result.data?.disputeId,
                        numberCallToPolice: result.data?.alarmPhoneNumber,
                        jurisdiction: result.data?.jurisdictionUnit,
                        disputeType: result.data?.alarmCategory,
                        disputeSubtype: result.data?.alarmSubcategory,
                        feedbackUnit: result.data?.feedbackUnit,
                        idOfCallToPolice: result.data?.alarmPersonIdCard,
                        casePlace: result.data?.caseAddress,
                        caseLevel: result.data?.policeLevel,
                        isCriminalCaseSolved: result.data?.isSolvedCriminalCase,
                        isPublicSecurityCaseFound: result.data?.isHandlingPublicSecurityCase,
                        isDisputeCaseResolved: result.data?.isResolvingDispute,
                        sensitiveCase: result.data?.sensitiveCase,
                        subjectOfCase: result.data?.caseReason,
                        isExpanded: true,
                    }
                }

                if (result.data?.disputeSource === '协同办案') {

                    return {
                        type: 'joint_investigation',
                        date: result.data?.alarmTime,
                        title: result.data?.disputeType,
                        content: result.data?.briefCaseDescription,
                        policeContent: result.data?.policeContent,
                        caseStatus: result.data?.caseStatus,
                        caseCode: result.data?.disputeId,
                        caseName: result.data?.caseTitle,
                        startTimeOfIncident: result.data?.crimeStartTime,
                        illegalInfo: result.data?.illegalInformation,
                        punishCategory: result.data?.penaltyType,
                        peopleInvolvedCaseCategory: result.data?.personnelInvolvedCategory,
                        crimeSceneDetailAddress: result.data?.caseLocationDetails,
                        currentCoerciveMeasure: result.data?.currentCompulsoryMeasures,
                        illegalAct: result.data?.illegalAct,
                        illegalDegree: result.data?.illegalDegree,
                        caseCharges: result.data?.involvedCharge,
                        prosecutionNumber: result.data?.involvedCharge,
                        prosecuteDecisionDate: result.data?.prosecutionDecisionTime,
                        charges: result.data?.prosecutionCharge,
                        actionCause: result.data?.caseReason,
                        isExpanded: true,
                    }
                }
            }

            return undefined
        }
    })

    if (status === 'pending') {
        return (
            <div className='h-[70%] grid place-content-center'>
                <Spin size="large"/>
            </div>
        )
    }

    if (status === 'error') {
        return null
    }

    if (status === 'success') {

        if (data?.type === 'police_case') {
            return (
                <PoliceCase type={data.type} {...data} />
            )
        }

        if (data?.type === 'joint_investigation') {
            return (
                <JointInvestigation type={data.type} {...data} />
            )
        }

        return null
    }
}

function BasicInfoContainer () {
    const selectedDisputeThumbnail = useAtomValue(selectedDisputeThumbnailAtom)
    
    const { data, status } = useQuery({
        queryKey: ['basic_info', selectedDisputeThumbnail?.id],
        queryFn: async () => {
            const data = await apiClient.post(
                `portraitAnalysis/citizenInfo`,
                {
                    json: {
                        idCard: selectedDisputeThumbnail?.id,
                    }
                },
            ).json()

            return data
        },
        enabled: !!selectedDisputeThumbnail?.id,
        select: (result) => {
            if (result.code === 200) {
                return {
                    name: result.data?.citizenInfo?.name,
                    gender: result.data?.citizenInfo?.gender,
                    age: result.data?.citizenInfo?.age,
                    place: result.data?.citizenInfo?.registeredResidenceAddress,
                    idNumber: result.data?.citizenInfo?.idCard,
                    avatarUrl: result.data?.citizenInfo?.avatarUrl,
                    phoneList: arrayHelper(result.data?.phoneList).slice(0, 3).map((item) => {
                        return {
                            tel: item?.phone,
                            dispute: item?.count,
                        }
                    }),
                    address: {
                        placeOfRegion: result.data?.citizenInfo?.nativePlace,
                        residenceAddress: result.data?.citizenInfo?.registeredResidenceAddress,
                    },
                    tagList: arrayHelper(result.data?.tagList).map((item) => {
                        return {
                            name: item?.tagName,
                            isHightLight: item?.highlight,
                        }
                    }),
                    wordCloudList: arrayHelper(result.data?.disputeWordList).map((item) => {
                        return {
                            name: item?.name,
                            value: item?.count,
                        }
                    })
                }
            }

            return undefined
        }
    })

    if (status === 'pending') {
        return (
            <div className='h-[70%] grid place-content-center'>
                <Spin size="large"/>
            </div>
        )
    }

    if (status === 'error') {
        return null
    }

    if (status === 'success') {
        return (
            <BasicInfo {...data} />
        )
    }
}

function DisputeHistoryContainer () {
    const selectedDisputeThumbnail = useAtomValue(selectedDisputeThumbnailAtom)
    const { data, status } = useQuery({
        queryKey: ['dispute_history', selectedDisputeThumbnail?.id, 0, 0],
        queryFn: async () => {
            const data = await apiClient.post(
                `portraitAnalysis/disputeHistory`,
                {
                    json: {
                        idCard: selectedDisputeThumbnail?.id,
                        statisticsType: 0,
                        associationType: 0,
                    }
                },
            ).json()

            return data
        },
        enabled: !!selectedDisputeThumbnail?.id,
        select: (result) => {
            if (result.code === 200) {
                return arrayHelper(result.data).map((item) => {
                    if (item?.disputeSource === '110警情') {
                        return {
                            type: 'police_case',
                            date: item?.alarmTime,
                            title: item?.disputeType,
                            content: item?.alarmContent,
                            feedback: item?.policeResponse,
                            policeCaseNumber: item?.disputeId,
                            numberCallToPolice: item?.alarmPhoneNumber,
                            jurisdiction: item?.jurisdictionUnit,
                            disputeType: item?.alarmCategory,
                            disputeSubtype: item?.alarmSubcategory,
                            feedbackUnit: item?.feedbackUnit,
                            idOfCallToPolice: item?.alarmPersonIdCard,
                            casePlace: item?.caseAddress,
                            caseLevel: item?.policeLevel,
                            isCriminalCaseSolved: item?.isSolvedCriminalCase,
                            isPublicSecurityCaseFound: item?.isHandlingPublicSecurityCase,
                            isDisputeCaseResolved: item?.isResolvingDispute,
                            sensitiveCase: item?.sensitiveCase,
                            subjectOfCase: item?.caseReason,
                            isExpanded: true,
                        }
                    }
        
                    if (item?.disputeSource === '协同办案') {
                        return {
                            type: 'joint_investigation',
                            date: item?.alarmTime,
                            title: item?.disputeType,
                            content: item?.briefCaseDescription,
                            policeContent: item?.policeContent,
                            caseStatus: item?.caseStatus,
                            caseCode: item?.disputeId,
                            caseName: item?.caseTitle,
                            startTimeOfIncident: item?.crimeStartTime,
                            illegalInfo: item?.illegalInformation,
                            punishCategory: item?.penaltyType,
                            peopleInvolvedCaseCategory: item?.personnelInvolvedCategory,
                            crimeSceneDetailAddress: item?.caseLocationDetails,
                            currentCoerciveMeasure: item?.currentCompulsoryMeasures,
                            illegalAct: item?.illegalAct,
                            illegalDegree: item?.illegalDegree,
                            caseCharges: item?.involvedCharge,
                            prosecutionNumber: item?.involvedCharge,
                            prosecuteDecisionDate: item?.prosecutionDecisionTime,
                            charges: item?.prosecutionCharge,
                            actionCause: item?.caseReason,
                            isExpanded: true,
                        }
                    }
                })
                .filter((item) => (item !== undefined))
            }
        
            return []
        }
    })

    if (status === 'pending') {
        return (
            <div className='h-[70%] grid place-content-center'>
                <Spin size="large"/>
            </div>
        )
    }

    if (status === 'error') {
        return null
    }

    if (status === 'success') {

        const list = data.map((item) => {
            if (item.type === 'police_case') {
                return {
                    children: (<PoliceCase type={item.type} {...item} />)
                }
            }

            if (item.type === 'joint_investigation') {
                return {
                    children: (<JointInvestigation type={item.type} {...item} />)
                }
            }
        })
        .filter((item) => (item !== undefined))

        return (
            <Timeline items={list}/>
        )
    }

}

export default function GraphDrawerContent ({ type }) {

    const selectedDisputeThumbnail = useAtomValue(selectedDisputeThumbnailAtom)

    let tabItems = []

    if (selectedDisputeThumbnail?.nodeType === 'dispute') {
        tabItems = [
            {
                key: '1',
                label: '简介',
                children: (<DisputeInfoContainer />)
            },
        ]
    }

    if (selectedDisputeThumbnail?.nodeType === 'people') {
        tabItems = [
            {
                key: '1',
                label: '基本信息',
                children: (
                    <div className=' mx-3'>
                        <BasicInfoContainer />
                    </div>
                )
            },
            {
                key: '2',
                label: '历史纠纷',
                children: (
                    <DisputeHistoryContainer />
                )
            },
        ]
    }

    // if (type === '3') {
    //     tabItems = [
    //         {
    //             key: '1',
    //             label: '简介',
    //             children: (<DisputeInfoContainer />)
    //         },
    //     ]
    // }

    return (
        <div>
            <Tabs
                id='graph-drawer-content'
                defaultActiveKey='1'
                size='small'
                items={tabItems}
                tabBarExtraContent={{
                    right: (<Close />)
                }}
            />
        </div>
    )
}